package com.acce.core.controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.justobjects.pushlet.core.Dispatcher;
import nl.justobjects.pushlet.core.Event;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.acce.core.config.CarParkArea;
import com.acce.core.config.ReturnCodes;
import com.acce.core.pojo.ArgsPojo;
import com.acce.core.pojo.CarPack;
import com.acce.core.pojo.CompanyDepartment;
import com.acce.core.pojo.CompanyList;
import com.acce.core.pojo.EmployeeInfo;
import com.acce.core.pojo.FeeCount;
import com.acce.core.pojo.Goods;
import com.acce.core.pojo.InquiryHeader;
import com.acce.core.pojo.InquiryList;
import com.acce.core.pojo.PurchaseHeader;
import com.acce.core.pojo.PurchaseList;
import com.acce.core.pojo.QuoteHeader;
import com.acce.core.pojo.QuoteList;
import com.acce.core.pojo.ReturnPojo;
import com.acce.core.pojo.UserList;
import com.acce.core.utils.Constants;
import com.acce.core.utils.EncodingTool;
import com.acce.core.utils.PropertiesUtil;
import com.acce.core.utils.TokenUtils;
import com.acce.core.utils.Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
public class MarketViewController extends BaseController{

	Logger logger = Logger.getLogger(MarketViewController.class);
	String preModular = "wape-web";
	String authPath = PropertiesUtil.getInstance().getProperties("/system.properties").getProperty("authPath");
	String productPath = PropertiesUtil.getInstance().getProperties("/system.properties").getProperty("productPath");
	String wapeWechatAppID = PropertiesUtil.getInstance().getProperties("/system.properties").getProperty("wapeWechatAppID");
	String wapeWechatAppSecret = PropertiesUtil.getInstance().getProperties("/system.properties").getProperty("wapeWechatAppSecret");

	@RequestMapping("/view/market")
	public void center(@ModelAttribute("argsPojo")ArgsPojo args,HttpServletRequest request, HttpServletResponse response, HttpSession httpSession){
		String serviceCode=args.getServiceCode();
		if(serviceCode.equals("MMZS108")){
	    	queryShed(args,response,request,httpSession);
	    }
	}
	
	/**
	 * view market.jsp
	 * 查询市场铺位区域信息
	 * @param args
	 * @param response
	 */
	private void queryShed(ArgsPojo args, HttpServletResponse response, HttpServletRequest request, 
			HttpSession httpSession ){
		String serviceAddrgs = authPath;
		String atUserId=(String) httpSession.getAttribute("atUserId");
		String token=(String) httpSession.getAttribute("token");
		String serviceCode = args.getServiceCode();
		String timestamp = Utils.getCurrTimeMillions();
	    String nonce = Utils.getNonce();
	    String sign = "";
		try {
			sign = TokenUtils.getSign(token, timestamp, nonce);
		} catch (NoSuchAlgorithmException e3) {
			logger.error("sign make error::" + e3.getMessage());
		}
	    String editUserId = atUserId;
	    String editTime = Utils.getCurrTime();
	    String ipaddr = "";
		try {
			ipaddr = Utils.getIpAddress(request);
		} catch (IOException e2) {
			logger.error("ip not get::" + e2.getMessage());
		}
	    String device = "pc";
	    String mac = "00-00-00-00-000";
	    
	    UserList userlist =(UserList) httpSession.getAttribute("user");
		
		//表示不同的车位区域, 1000:大棚区, 1200:临时区, 1300:蔬菜区, 1400:海鲜区, 1500:冻品, 1600
	    String t_p = args.getT_p();
	    if(t_p == null) t_p = "1000";
	    List<String> list = new ArrayList<String>();
	    for(CarParkArea cpa:CarParkArea.values()) {
	    	list.add(cpa.getType());
	    }
		if(null == userlist){//用户未登陆
        	String remsg = "用户会话已失效, 请重新登录!";
        	try {
        		request.setAttribute("remsg", remsg);
				request.getRequestDispatcher("/3g/login.jsp").forward(request, response);
			} catch (Exception e) {
				logger.info("wape-web::queryShed::userlist is null" + e.getMessage());
			}
		}else{
			JSONObject json = new JSONObject();
			json.put("atUserId", atUserId);
		    json.put("type", "2");
		    json.put("parkArea", t_p);
		    StringBuffer buff=new StringBuffer();
			buff.append(json.toJSONString());
		    String business = json.toString();
	        // 创建参数队列    
		    Map<String, String> params = new HashMap<String, String>();
			params.put("serviceCode", serviceCode);
			params.put("sign", sign);
			params.put("timestamp", timestamp);
			params.put("nonce", nonce);
			params.put("editUserId", editUserId);
			params.put("editTime", editTime);
			params.put("ipaddr", ipaddr);
			params.put("device", device);
			params.put("mac", mac);
			params.put("realName", userlist.getRealName());
			params.put("companyId", userlist.getCompanyId());
			params.put("companyName", userlist.getCompanyName());
			params.put("departmentId", userlist.getDepartmentId());
			params.put("departmentName", userlist.getDepartmentName());
			params.put("business", business);
	        String serviceString = sendhttp(serviceAddrgs, params);
	        JSONObject serviceJson=JSON.parseObject(serviceString);
    		JSONObject result = serviceJson.getJSONObject("result");
            if(null != result){
        		JSONArray parkArea = result.getJSONArray("parkArea");
        		JSONArray parkPos = result.getJSONArray("parkPos");
        		JSONObject parks = result.getJSONObject("parks");
        		request.setAttribute("parkArea", t_p);
        		List<CompanyDepartment> parkAreaList = JSONArray.toJavaObject(parkArea, List.class);
        		request.setAttribute("parkAreaList", parkAreaList);
        		List<CompanyDepartment> parkPosList = JSONArray.toJavaObject(parkPos, List.class);
        		request.setAttribute("parkPosList", parkPosList);
        		Map<String,List<CompanyDepartment>> parkList = JSONArray.toJavaObject(parks, Map.class);
        		request.setAttribute("parkList", parkList);
            }
	        
            if("200".equals(serviceJson.get("returnCode"))){
            	try {
            		request.setAttribute("carParkArea", t_p);
					request.getRequestDispatcher("/3g/mmzs/parking.jsp").forward(request, response);
				} catch (Exception e) {
					logger.info("wape-web::queryShed::" + e.getMessage());
				}
            }else{
            	String remsg = "系统错误, 请联系管理员!";
            	remsg = serviceJson.getString("returnMsg");
            	try {
            		request.setAttribute("remsg", remsg);
					request.getRequestDispatcher("/3g/mmzs/yuexi.jsp").forward(request, response);
				} catch (Exception e) {
					logger.info("wape-web::queryShed::" + e.getMessage());
				}
            }
		}
	}
	
}
